<template>
  <div class="app-container">
    <!-- 搜索栏开始 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      style="margin-top: -15px"
    >
      <el-form-item label="用户名称" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名称"
          clearable
          style="width: 260px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号码"
          clearable
          style="width: 260px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="用户状态"
          clearable
          style="width: 260px"
        >
          <el-option
            v-for="item in userStatusList"
            :key="item.key"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 搜索栏结束 -->

    <!-- 按钮开始 -->
    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          >删除
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>
    <!-- 按钮结束 -->

    <!-- 表格数据开始 -->
    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" width="50" />
      <el-table-column
        label="用户编号"
        key="userId"
        prop="userId"
        align="center"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="用户名称"
        key="username"
        prop="username"
        align="center"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="用户昵称"
        key="nickName"
        prop="nickName"
        align="center"
        v-if="columns[2].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="角色"
        key="roleId"
        prop="roleId"
        align="center"
        v-if="columns[3].visible"
      >
        <template #default="scope">
          <el-tag>
            {{ getRoleName(scope.row.roleId) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="性别"
        key="sex"
        prop="sex"
        align="center"
        v-if="columns[4].visible"
      >
        <template #default="scope">
          <el-tag type="success">
            {{ getGender(scope.row.sex) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="手机号码"
        key="phoneNumber"
        prop="phoneNumber"
        align="center"
        v-if="columns[5].visible"
      />
      <el-table-column
        label="邮箱"
        key="phoneNumber"
        prop="phoneNumber"
        align="center"
        v-if="columns[6].visible"
      />
      <el-table-column
        label="状态"
        key="status"
        align="center"
        v-if="columns[7].visible"
      >
        <template #default="scope">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.status"
            :before-change="beforeChange"
            @change="handleStatusChange(scope.row)"
            :disabled="scope.row.roleId === 1"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        v-if="columns[8].visible"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="createTime"
        v-if="columns[9].visible"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <span style="margin-left: 10px">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-if="scope.row.roleId !== 1"
              />
            </span>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <span style="margin-left: 10px">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-if="scope.row.roleId !== 1"
              />
            </span>
          </el-tooltip>
          <el-tooltip content="重置密码" placement="top">
            <span style="margin-left: 10px">
              <el-button
                link
                type="primary"
                icon="Key"
                @click="handleResetPwd(scope.row)"
                v-if="scope.row.roleId !== 1"
              />
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格数据结束 -->

    <!-- 分页开始 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 分页结束 -->

    <!-- 添加或修改用户对话框开始 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="form.userId === undefined"
              label="用户账号"
              prop="username"
            >
              <el-input
                v-model="form.username"
                placeholder="请输入用户账号"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="form.userId === undefined"
              label="用户密码"
              prop="password"
            >
              <el-input
                v-model="form.password"
                placeholder="请输入用户密码"
                type="password"
                maxlength="20"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="form.nickName"
                placeholder="请输入用户昵称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option
                  v-for="item in userSexList"
                  :key="item.key"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input
                v-model="form.phoneNumber"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="form.roleId" placeholder="请选择">
                <el-option
                  v-for="item in roleList"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status === 0"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="item in userStatusList"
                  :key="item.key"
                  :label="item.key"
                  >{{ item.value }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改用户对话框结束 -->
  </div>
</template>

<script setup name="User">
import { getCurrentInstance, nextTick, reactive, ref, toRefs } from "vue";
import { ElMessageBox } from "element-plus";
import * as userApi from "@/api/system/userApi";
import * as roleApi from "@/api/system/roleApi";

const { proxy } = getCurrentInstance();

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const initPassword = ref(undefined);
const roleOptions = ref([]);
const switchState = ref(false);

const roleList = ref([]);
const userStatusList = ref([
  { key: 0, value: 0, label: "停用" },
  { key: 1, value: 1, label: "正常" },
]);
const userSexList = ref([
  { key: 0, value: 0, label: "未知" },
  { key: 1, value: 1, label: "男" },
  { key: 2, value: 2, label: "女" },
]);
const columns = ref([
  { key: 0, label: "用户编号", visible: true },
  { key: 1, label: "用户名称", visible: true },
  { key: 2, label: "用户昵称", visible: true },
  { key: 3, label: "角色", visible: true },
  { key: 4, label: "性别", visible: true },
  { key: 5, label: "手机号码", visible: true },
  { key: 6, label: "邮箱", visible: true },
  { key: 7, label: "状态", visible: true },
  { key: 8, label: "创建时间", visible: true },
  { key: 9, label: "更新时间", visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: undefined,
    phoneNumber: undefined,
    status: undefined,
  },
  rules: {
    username: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "用户名称长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" },
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        min: 5,
        max: 20,
        message: "用户密码长度必须介于 5 和 20 之间",
        trigger: "blur",
      },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phoneNumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
});
const { form, queryParams, rules } = toRefs(data);

/** 查询用户列表 */
function getList() {
  loading.value = true;
  userApi
    .listUser(queryParams.value)
    .then((res) => {
      userList.value = res.data.records;
      total.value = res.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 查询用户列表 */
function getRoleList() {
  roleApi.listRole().then((res) => {
    roleList.value = res.data.records;
  });
}

/** 根据性别值返回对应性别 */
function getGender(sex) {
  let gender = "";
  userSexList.value.some((item) => {
    gender = item.label;
    return sex === item.value;
  });
  return gender;
}

/** 根据角色ID返回对应角色名称 */
function getRoleName(roleId) {
  let roleName = "";
  roleList.value.some((item) => {
    roleName = item.roleName;
    return roleId === item.roleId;
  });
  return roleName;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  userApi.getUserDetail().then((res) => {
    roleOptions.value = res.data.roles;
    open.value = true;
    title.value = "添加用户";
    form.value.password = initPassword.value;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const userId = row.userId || ids.value;

  userApi.getUserDetail(userId).then((res) => {
    open.value = true;
    form.value = res.data.userDTO;
    title.value = "修改用户";
    nextTick(() => {
      getRoleList();
      // roleApi.listRole(queryParams.value).then((res) => {
      //   roleList.value = res.data.records;
      // });
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.userRef.validate((valid) => {
    if (valid) {
      if (form.value.userId !== undefined) {
        userApi.updateUser(form.value).then(() => {
          open.value = false;
          getList();
        });
      } else {
        userApi.addUser(form.value).then(() => {
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId || ids.value;
  ElMessageBox.confirm(`是否确认删除用户编号为[${userIds}]的数据项？`)
    .then(() => userApi.deleteUser(userIds))
    .then(() => {
      getList();
    })
    .catch(() => {});
}

/** 开关切换  */
function beforeChange() {
  return new Promise((resolve) => {
    switchState.value = true;
    return resolve(true);
  });
}

/** 用户状态修改  */
function handleStatusChange(row) {
  if (switchState.value) {
    switchState.value = false;
    const text = row.status === true ? "停用" : "启用";
    ElMessageBox.confirm(`确认要${text}用户[${row.username}]吗?`)
      .then(() => userApi.changeUserStatus(row.userId, row.status))
      .catch(() => {
        row.status = row.status === 0 ? 1 : 0;
      });
  }
}

/** 修改密码按钮操作 */
function handleResetPwd(row) {
  ElMessageBox.prompt(`请输入"${row.username}"的新密码`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{6,20}$/,
    inputErrorMessage: "用户密码长度必须介于 6 和 20 之间",
  }).then(({ value }) => {
    userApi.resetUserPassword(row.userId, value);
  });
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    username: undefined,
    nickName: undefined,
    password: undefined,
    phoneNumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    roleId: undefined,
  };
  proxy.resetForm("userRef");
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

getList();
getRoleList();
</script>
